package edu.hit.stu.controller;

import edu.hit.stu.config.IReactiveUserDetailsServiceImpl;
import edu.hit.stu.controller.dto.AuthDto;
import edu.hit.stu.util.common.IPrint;
import edu.hit.stu.util.jwt.JwtProperties;
import edu.hit.stu.util.jwt.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import javax.validation.Valid;

/**
 * @author 刘智彬
 */
@RestController
@RequiredArgsConstructor
public class LoginResource {

    private final IReactiveUserDetailsServiceImpl iReactiveUserDetailsService;
    private final PasswordEncoder passwordEncoder;
    private final JwtProperties jwtProperties;

    @PostMapping(path = "/authentication", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Mono<ResponseEntity<String>> login(@Valid @RequestBody AuthDto authDto) {
        Mono<UserDetails> user = iReactiveUserDetailsService.findByUsername(authDto.getUsername());
        user.flatMap(userDetails -> Mono.just(userDetails.toString()))
                .subscribe(IPrint::printWithColorNoBg);
//        TODO 验证权限？
        return user.filter(userDetails -> passwordEncoder.matches(authDto.getPassword(), userDetails.getPassword()))
                .flatMap(userDetails -> {
                    assert userDetails != null: "密码不匹配!";
                    String token = JwtUtil.creatToken(userDetails);
                    token = jwtProperties.getPrefix() + token;
                    return Mono.just(ResponseEntity.badRequest().body(token));
                });
    }
}
